package com.feng.zhihao.apigeteway.config.shiro;

import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.ExcessiveAttemptsException;
import org.apache.shiro.authc.SimpleAuthenticationInfo;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.springframework.beans.factory.annotation.Autowired;

import com.feng.zhihao.apigeteway.dao.user.UserInfoDao;
import com.feng.zhihao.apigeteway.entity.UserInfo;

public class AuthRealm extends AuthorizingRealm {

	@Autowired
	UserInfoDao userInfoRepository;
	// 认证.登录
	@Override
	protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
		UsernamePasswordToken utoken = (UsernamePasswordToken) token;// 获取用户输入的token
		String username = utoken.getUsername();
		UserInfo userInfo=userInfoRepository.findOne(username);
		if(userInfo != null){
			SimpleAuthenticationInfo simpleAuthenticationInfo=new SimpleAuthenticationInfo(userInfo, userInfo.getPassword(), this.getClass().getName());
			if(userInfo.getChannelInfo().getChannelState() == 0){
				throw new ExcessiveAttemptsException("渠道已经关闭");
			}
			return simpleAuthenticationInfo;// 放入shiro.调用CredentialsMatcher检验密码	
		}else{
			return null;
		}
		
	}

	// 授权
	@Override
	protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principal) {
		SimpleAuthorizationInfo info = new SimpleAuthorizationInfo();
		return info;
	}

}